package concurrent.pcpattern;

import java.text.MessageFormat;
import java.util.Random;
import java.util.concurrent.LinkedBlockingQueue;

public class Consumer implements Runnable {

    private static final int SLEEPTIME = 1000;
    private LinkedBlockingQueue<PCData> queue;

    public Consumer(LinkedBlockingQueue<PCData> queue) {
        this.queue = queue;
    }

    @Override
    public void run() {

        System.out.println("start Consumer id= " + Thread.currentThread().getId());

        Random r = new Random();
        try {
            while (true) {
                PCData pcData = queue.take();
                if (pcData != null) {
                    int re = pcData.getData() * pcData.getData();
                    System.out.println(MessageFormat.format("{0}*{1}={2}",
                            pcData.getData(), pcData.getData(), re));
                    Thread.sleep(r.nextInt(SLEEPTIME));
                }
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
            Thread.currentThread().interrupt();
        }
    }
}
